import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import { Route } from '@/models/connect';
import XLSX from 'xlsx'
import { Link } from 'react-router-dom'
import { AUTH_TOKEN } from './request';

export function filterList(rawData, key) {
  var newList = []
  var _rawData = rawData.dataSource
  for (var i = 0; i < _rawData.length; i++) {
    for (var k in _rawData[i]) {
      // if (
      //   isObject(rawData[i][k]) ?
      //     JSON.stringify(rawData[i][k]) > -1 : rawData[i][k].indexOf(key) > -1
      // )
      // {
      //   newList.push(rawData[i])
      //   break
      // }
      if (_rawData[i][k].toString().indexOf(key) > -1) {
        newList.push(_rawData[i])
        break
      }
    }
  }
  return newList

}

export const downloadFileByData = async (data: { blob: () => any; }, name: string) => {
  if (!data || !name) {
    return;
  }
  const blob = await data.blob();
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', name);
  link.click();

}

export function openDownloadDialog(url: string, saveName: string) {
  if (typeof url == 'object' && url instanceof Blob) {
    url = URL.createObjectURL(url); // 创建blob地址
  }
  const aLink = document.createElement('a');
  aLink.href = url;
  aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
  let event;
  if (window.MouseEvent) event = new MouseEvent('click');
  else {
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  }
  aLink.dispatchEvent(event);
}

export function sheet2blob(sheet, sheetName) {
  sheetName = sheetName || 'sheet1';
  var workbook = {
    SheetNames: [sheetName],
    Sheets: {}
  };
  workbook.Sheets[sheetName] = sheet;
  // 生成excel的配置项
  var wopts = {
    bookType: 'xlsx', // 要生成的文件类型
    bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    type: 'binary'
  };
  var wbout = XLSX.write(workbook, wopts);
  var blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });
  // 字符串转ArrayBuffer
  function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
  return blob;
}

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */
export const getAuthorityFromRouter = <T extends Route>(
  router: T[] = [],
  pathname: string,
): T | undefined => {
  const authority = router.find(
    ({ routes, path = '/', target = '_self' }) =>
      (path && target !== '_blank' && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};

export const getRouteAuthority = (path: string, routeData: Route[]) => {
  let authorities: string[] | string | undefined;
  routeData.forEach((route) => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      }
      // exact match
      if (route.path === path) {
        authorities = route.authority || authorities;
      }
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};
// 计算
export const checkResult = (n?: number, o?: number) => {
  return ((n || 0) / (o || 0) * 100).toFixed(1);
}
export const downloadFile = (filename: any, fileUrl: any, type: any) => {
  const token = localStorage.getItem('token');//
  const authToken = localStorage.getItem(AUTH_TOKEN)
  const xhr = new XMLHttpRequest()
  const url = fileUrl;//请求的api
  xhr.open('get', url, true)
  xhr.setRequestHeader('x-access-token', `${token}`) // 给后端发送请求头
  xhr.setRequestHeader('Authorization', `Bearer ${authToken}`) // 给后端发送请求头
  xhr.responseType = 'blob'
  xhr.onload = function (e) {
    if (this.status === 200) {
      const blob = this.response
      const urlObject = window.URL || window.webkitURL || window
      const export_blob = new Blob([blob])
      const a = document.createElement('a') // 利用a标签特性下载
      const url = urlObject.createObjectURL(export_blob)
      a.href = url
      a.download = filename + type
      a.click()
    }
  }
  xhr.send()
}

export const xlsxHost = process.env.REACT_APP_ENV === 'local' ? '/app-admin' : '/api'
